package com.nutrition.health.repository;

import com.nutrition.health.model.DietRecord;
import com.nutrition.health.model.DietRecord.MealType;
import com.nutrition.health.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface DietRecordRepository extends JpaRepository<DietRecord, Long> {
    
    List<DietRecord> findByUser(User user);
    
    Page<DietRecord> findByUser(User user, Pageable pageable);
    
    List<DietRecord> findByUserAndMealType(User user, MealType mealType);
    
    List<DietRecord> findByUserAndConsumptionTimeBetween(
            User user, 
            LocalDateTime startTime, 
            LocalDateTime endTime);
    
    @Query("SELECT dr FROM DietRecord dr JOIN dr.foodItems fi " +
           "WHERE dr.user = :user AND fi.id = :foodItemId")
    List<DietRecord> findByUserAndFoodItemId(
            @Param("user") User user, 
            @Param("foodItemId") Long foodItemId);
    
    @Query("SELECT SUM(ni.calories) FROM DietRecord dr " +
           "JOIN dr.foodItems fi " +
           "JOIN fi.nutritionInfo ni " +
           "WHERE dr.user = :user AND " +
           "dr.consumptionTime BETWEEN :startTime AND :endTime")
    Double calculateTotalCaloriesForUserInTimeRange(
            @Param("user") User user,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime);
    
    @Query("SELECT SUM(ni.protein) FROM DietRecord dr " +
           "JOIN dr.foodItems fi " +
           "JOIN fi.nutritionInfo ni " +
           "WHERE dr.user = :user AND " +
           "dr.consumptionTime BETWEEN :startTime AND :endTime")
    Double calculateTotalProteinForUserInTimeRange(
            @Param("user") User user,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime);
}